package com.filldream.fastboot.common.stockUtils.qt;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.UnicodeUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.filldream.fastboot.common.entity.R;
import com.filldream.fastboot.common.entity.db.StockBaseInfo;
import com.filldream.fastboot.common.stockUtils.qt.entity.StockInfo;
import com.filldream.fastboot.common.util.RandomUtil;
import org.apache.commons.lang3.ObjectUtils;
import java.util.*;

/**
 * 股票工具类
 */
public class StockUtil {

    /**
     * 获取单个股票实时行情信息
     * @param code  股票代码
     * @return  StockInfo
     */
    public static StockInfo getByCode(String code){
        List<StockInfo> list = getByCodes(Arrays.asList(code));
        return ObjectUtils.isNotEmpty(list) ? list.get(0) : null ;
    }

    /**
     * 获取多个股票实时行情信息
     * @param codes 股票代码列表
     * @return  List<StockInfo>
     */
    public static List<StockInfo> getByCodes(List<String> codes){
        return getByCodes(String.join(",", codes));
    }

    /**
     * 获取多个股票实时行情信息
     * @param codes 股票代码，多个代码用逗号分隔
     * @return  List<StockInfo>
     */
    public static List<StockInfo> getByCodes(String codes){
        List<StockInfo> resultList = new ArrayList<>();
        String stockInfoJson;
        try {
            stockInfoJson = HttpUtil.get( "https://qt.gtimg.cn/q="  + codes + "&tt=" + RandomUtil.randomNumByInterval(1,9999999) );
        }catch (Exception e){
            System.out.println("获取股票信息失败:" + e.getMessage());
            return Collections.emptyList();
        }
        String[] split = stockInfoJson.split(";");
        for (String item : split) {
            item = item.trim();
            if( item.contains("=") ){
                String itemResult = item.substring(item.indexOf("\"") + 1, item.lastIndexOf("\""));
                StockInfo stockInfo = new StockInfo().init(itemResult);
                resultList.add(stockInfo);
            }
        }
        return resultList;
    }

    /**
     * 是否在交易时间内
     * @return  返回boolean
     */
    public static boolean isInTime(Boolean isHoliday){
        //判断当前日期是否是交易日
        if( isInDay(isHoliday) ){
            //判断时间是否可以交易
            DateTime amStart = DateUtil.parse( "09:30:00",  "HH:mm:ss");
            DateTime amEnd = DateUtil.parse("11:30:00", "HH:mm:ss");
            DateTime pmStart = DateUtil.parse("13:00:00", "HH:mm:ss");
            DateTime pmEnd = DateUtil.parse("15:00:00", "HH:mm:ss");
            DateTime nowTime = DateUtil.parse(DateUtil.now().substring(11), "HH:mm:ss");
            return DateUtil.isIn(nowTime, amStart, amEnd) || DateUtil.isIn(nowTime, pmStart, pmEnd);
        }
        return false;
    }

    /**
     * 是否在交易日
     * 周六周日一律为休市时间，不管是否是节假日
     * @return  返回boolean
     */
    public static boolean isInDay(Boolean isHoliday){
        int day = DateUtil.dayOfWeek(new Date());
        return day != 1 && day != 7 && !isHoliday;
    }

    /**
     * 所有股票代码
     * @return
     */
    public static List<StockInfo> allStock(){
        String result = HttpUtil.get("http://api.jinshuyuan.net/get_stk_dic");
        result = result.replaceAll("sid,stkcd,stknm<br/>", "");
        String[] stockCodes   = result.split("<br/>");
        List<StockInfo> resultList = new ArrayList<>();
        for (String item : stockCodes) {
            String[] params = item.split(",");
            StockInfo stockInfo = new StockInfo();
            stockInfo.setCode(params[1].toLowerCase());
            stockInfo.setName(params[2]);
            resultList.add(stockInfo);
        }
        return resultList;
    }

    public static R<List<StockBaseInfo>> getStockCodeByName(String stockName){
        HttpRequest httpRequest = HttpUtil.createGet("https://ozone.10jqka.com.cn/tg_templates/doubleone/apiCenter/searchStock/index.php" +
                "?pattern=" + stockName +
                "&appname=lhbEnhanced" +
                "&_=1730689504197");
        httpRequest.header("user-agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36");
        httpRequest.header("origin","https://eq.10jqka.com.cn");
        httpRequest.header("referer","https://eq.10jqka.com.cn");
        String resultJson = httpRequest.execute().body();
        resultJson = UnicodeUtil.toString(resultJson);
        resultJson = resultJson.replaceAll("\"errorcode\":", "\"code\":");

        R<List<StockBaseInfo>> result = R.jsonToArr(resultJson, StockBaseInfo.class);
        List<StockBaseInfo> itemList = result.getData();
        itemList.forEach(item -> { item.initSearchCode(); });
        result.setData(itemList);
        return result;
    }

}